<template>
  <div>
    <el-card class="box-card">
      <el-form :inline="true" class="form-container" :model="configForm" ref="queryForm">
        <div class="search">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
                filterable
                remote
                :remote-method="getCustomers"
                :loading="loading"
                v-model="configForm.customerId"
                placeholder="请输入客户名称"
            >
              <el-option
                  v-for="item in customerOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="施工地址" prop="engineerProjectId">
            <el-select
                v-model="configForm.engineerProjectId"
                placeholder="请选择施工地址"
                @change="initTable"
            >
              <el-option
                  v-for="item in engineerProjectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="exportExcel">导出</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="setDisCountRate">设置折扣率</el-button>
        </div>
        <div class="func">
          <el-button icon="el-icon-plus" type="primary" @click="handleAdd">添加</el-button>
        </div>
      </el-form>
      <div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="Number.isNaN(configForm.directPrice)?0:configForm.directPrice"
                title="工程直接造价"
            >
              <template slot="prefix">
                <i class="el-icon-thumb" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-thumb" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="configForm.projectPrice"
                title="工程总造价"
            >
              <template slot="prefix">
                <i class="el-icon-star-on" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-star-on" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
                group-separator=","
                :precision="2"
                :value="configForm.discountPrice"
                title="折后价"
            >
              <template slot="prefix">
                <i class="el-icon-s-flag" style="color: red"></i>
              </template>
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: blue"></i>
              </template>
            </el-statistic>
          </el-col>
        </el-row>

      </div>

    </el-card>
    <el-table :data="budget.crafts"
              ref="lightCraftTable"
              style="width: 100%"
              border
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
              :data="props.row.budgetUnits"
              style="width: 100%"
              border
              height="500"
          >
            <el-table-column
                fixed
                label=""
                type="index"
            >
            </el-table-column>
            <el-table-column
                fixed
                prop="name"
                label="项目名称"
            >
            </el-table-column>
            <el-table-column
                fixed
                prop="unitName"
                label="单位"
            >
            </el-table-column>
            <el-table-column
                fixed
                prop="unitName"
                label="数量"
            >
              <template v-slot="scope">

                <div @dblclick="handleDisable">
                  <span v-if="scope.row.billingMethod===6">费率：{{ scope.row.rate }}</span>
                  <el-input v-model="scope.row.num" v-else :disabled="isDisabled" :class="isDisabled?'click-disable':''"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                fixed
                prop="salePrice"
                label="单价"
            >
            </el-table-column>
            <el-table-column
                fixed
                prop="unitName"
                label="合价"
            >
              <template v-slot="scope">
                <span>{{ scope.row.num * scope.row.salePrice }}</span>
              </template>
            </el-table-column>
            <el-table-column
                fixed
                prop="illustrate"
                :show-overflow-tooltip="true"
                label="工艺说明"
            >
            </el-table-column>

          </el-table>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="50"
      >

        <template v-slot="scope">
          <el-button type="success" icon="el-icon-plus" size="mini" circle @click="configCraft(scope.row)"></el-button>
        </template>
      </el-table-column>

      <el-table-column
          prop="name"
          label="项目名称"
      >
      </el-table-column>
      <el-table-column
          label="小计"
      >
        <template v-slot="scope">

          {{ subTotal(scope.row) }}
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        title="配置工艺"
        :visible.sync="isShow"
        width="70%"

    >
      <template slot="title">
        <el-card>
          <el-form :inline="true" :model="sourceForm" ref="sourceSearchForm">
            <el-form-item label="工艺名称" prop="name">
              <el-input
                  placeholder="请输入工艺名称"
                  prefix-icon="el-icon-search"
                  v-model="sourceForm.name"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="工艺类型" prop="illustrateType">
              <el-select
                  v-model="sourceForm.illustrateType"
                  placeholder="请选择工艺类型"
                  @change="initTable"
              >
                <el-option
                    v-for="item in illustrateTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-button icon="el-icon-search" type="success" @click="searchSource">搜索</el-button>
            <el-button icon="el-icon-refresh" type="success" class="reset_btn" @click="reset">重置</el-button>
          </el-form>
        </el-card>
      </template>
      <div class="table_container">

        <el-table
            class="table_item"
            border
            ref="sourceTable"
            :data="sourceData"
            style="width: 30%"
            height="500"
        >
          <el-table-column
              type="selection"
              width="55"
          >
          </el-table-column>
          <el-table-column
              prop="name"
              label="工艺名称"
          >
          </el-table-column>
          <el-table-column
              prop="unit"
              label="单位"
          >
            <template v-slot="scope">
              <span>{{ unitMap.get(scope.row.unit) }}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="salePrice"
              label="销售价"
          >
          </el-table-column>
          <el-table-column
              prop="illustrateType"
              label="工艺类型"
          >
            <template v-slot="scope">
              <span> {{ illustrateMap.get(scope.row.illustrateType) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="button_group">
          <el-button type="primary" icon="el-icon-arrow-left" @click="removeCraft"></el-button>
          <el-button type="primary" icon="el-icon-arrow-right" @click="addCraft"></el-button>
        </div>
        <el-table
            height="500"
            border
            class="table_item"
            ref="targetTable"
            :data="targetData"
            style="width: 30%"
        >
          <el-table-column
              type="selection"
              width="55"
          >
          </el-table-column>
          <el-table-column
              prop="name"
              label="工艺名称"
          >
          </el-table-column>
          <el-table-column
              prop="unit"
              label="单位"
          >
            <template v-slot="scope">
              <span>{{ unitMap.get(scope.row.unit)||scope.row.unitName }}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="salePrice"
              label="销售价"
          >
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="isShow = false">取 消</el-button>
          <el-button type="primary" @click="addBudget">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog
        title="设置折扣率"
        :visible.sync="disCountShow"
        width="20%"

    >
      <el-form :inline="true" class="form-container" :model="disCountForm" ref="disCountForm">
      <el-form-item label="折扣率" prop="discountRate">
          <el-input-number v-model="disCountForm.discountRate" :precision="2" :step="0.01" :max="1" :min="0"></el-input-number>
      </el-form-item>
      </el-form>
    <span slot="footer" class="dialog-footer">
          <el-button @click="disCountShow = false;disCountForm.discountRate=''">取 消</el-button>
          <el-button type="primary" @click="saveDiscount">确 定</el-button>
    </span>
    </el-dialog>
    <BudgetProject @loadBudget="loadBudget"
                   :customerId="configForm.customerId"
                   :budgetId="budget.id"
                   :engineerProjectId="configForm.engineerProjectId"
    >

    </BudgetProject>
  </div>

</template>

<script>
import Submenu from 'element-ui/packages/submenu'
import { listCustomer } from '@/api/intendedCustomer'
import { listEngineerProjects } from '@/api/engineerProject'
import { listCraft } from '@/api/craft'
import { listUnit } from '@/api/unit'
import { listProject } from '@/api/project'
import {
  exportLightExcel,
  getDiscountRate,
  getProjects,
  listBindCrafts,
  saveBatch,
  saveBudget,
  setDiscountRate
} from '@/api/budget'
import Page from '@/components/page/index.vue'
import BudgetProject from '@/views/budgetManagement/BudgetProject.vue'

export default {
  name: 'LightAuxiliaryBudget',
  data() {
    return {
      budget: {},
      sourceForm: {
        name: '',
        illustrateType: ''
      },
      disCountForm: {
        discountRate: '',
        id: ''
      },
      isDisabled: true,
      isShow: false,
      projectIsShow: true,
      disCountShow: false,
      loading: false,
      configForm: {
        discountRate: '',
        projectId: '',
        customerId: '',
        engineerProjectId: '',
        budgetId: '',
        directPrice: '',
        projectPrice: '',
        discountPrice: ''
      },
      customerOptions: [],
      engineerProjectOptions: [],
      illustrateTypeOptions: [
        { label: '水电工', value: 1 },
        { label: '木工', value: 2 },
        { label: '瓦工', value: 3 },
        { label: '油漆工', value: 4 },
        { label: '杂项', value: 8 }
      ],
      projectOptions: [],
      unitMap: new Map(),
      illustrateMap: new Map(),
      sourceData: [],
      targetData: []
    }
  },
  computed: {},
  components: {
    BudgetProject
  },
  watch: {
    'configForm.customerId'(newVal) {
      this.engineerProjectOptions = []
      this.configForm.engineerProjectId = ''
      listEngineerProjects(newVal).then(data => {
        this.loading = false
        if (data.length > 0) {
          this.engineerProjectOptions = data.map(n => {
            return {
              value: n.id,
              label: n.address
            }
          })
        }
      })
    },
    'budget.crafts': {
      deep: true,
      handler(newVal) {
        if (!newVal) {
          return
        }
        //工程直接造价
        let directPrice = newVal.filter(n => n.id !== 12).map(n => n.totalPrice).reduce((prev, cur) => prev + cur * 1, 0)
        this.configForm.directPrice = directPrice
        //工程总造价
        let totalPrice = newVal.map(n => n.totalPrice).reduce((prev, cur) => prev + cur * 1, 0)
        this.configForm.projectPrice = totalPrice
        this.configForm.discountPrice = totalPrice *  this.configForm.discountRate
      }
    }
  },
  mounted() {
    this.loadBasicData()
  },
  methods: {
    handleDisable() {
      console.log(11111)
      this.isDisabled = false
    },
    setDisCountRate() {
      if (this.configForm.engineerProjectId) {
        this.disCountShow = true
        this.disCountForm.id=this.configForm.engineerProjectId
      } else {
        this.$message({
          type: 'error',
          message: '请先选择施工地址!'
        })
      }
    },
    saveDiscount() {
      setDiscountRate(this.disCountForm).then(n=>{
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
        this.disCountShow = false
        this.configForm.discountRate=this.disCountForm.discountRate
        this.configForm.discountPrice= this.configForm.projectPrice*  this.configForm.discountRate
      })
    },
    save() {
      return new Promise((resolve, reject) => {
        let data = []
        if (!this.budget.crafts) {
          resolve()
        }
        this.budget.crafts.forEach(n => {
          let item = Object.assign({}, this.configForm)
          item.projectId = n.id
          item.crafts = n.budgetUnits
          data.push(item)
        })
        this.isDisabled=true
        saveBatch(data).then(n => {
          resolve()
          this.$message(
              {
                type: 'success',
                message: '操作成功!'
              }
          )
        })

      })

    },
    subTotal(row) {
      if (row.budgetUnits.length >= 1) {
        let totalPrice = 0
        if (row.id !== 12) {
          totalPrice = row.budgetUnits.reduce((prev, current) => prev + current.salePrice * current.num, 0)
          row.totalPrice = totalPrice
          return totalPrice.toFixed(2)
        } else {
          row.budgetUnits.forEach(n => {
            if (n.billingMethod === 6) {
              totalPrice += n.rate * this.configForm.directPrice
            } else {
              totalPrice += n.salePrice * n.num
            }
          })
          row.totalPrice = totalPrice
          return totalPrice.toFixed(2)
        }
      }
    },

    loadBudget() {

      //刷新table数据
      this.save().then(() => {
        this.$nextTick(() => {
          this.initTable()
        })

      })
      this.isDisabled=false
    },
    exportExcel() {
      if (this.configForm.customerId && this.configForm.customerId) {
        const fileUrl = `/api/budget/exportLightAuxiliary/${this.configForm.customerId}/${this.configForm.engineerProjectId}`
        const link = document.createElement('a')
        link.href = fileUrl
        link.setAttribute('download', '轻辅预算表.xlsx')
        link.click()

      } else {
        this.$message({
          type: 'error',
          message: '请选择客户和项目再导出!'
        })
      }
    },
    searchSource() {
      this.loadCraft()
    },
    reset() {
      this.$refs.sourceSearchForm.resetFields()
      this.loadCraft()
    },
    initTable() {
      this.isDisabled=true

      //初始化table数据
      //加载当前折扣率
      getDiscountRate(this.configForm.engineerProjectId).then((res)=>{
        this.configForm.discountRate = res.discountRate
        this.disCountForm.discountRate = res.discountRate
      })
      getProjects({
        customerId: this.configForm.customerId,
        engineerProjectId: this.configForm.engineerProjectId
      }).then(data => {
        this.budget = data

        if (!this.budget.crafts) {
          //清空顶部计算数据
          this.configForm.projectPrice = 0
          this.configForm.discountPrice = 0
          this.configForm.directPrice = 0

        }
      })
    },
    removeCraft() {
      let ids = this.$refs.targetTable.selection.map(n => n.id)
      this.targetData = this.targetData.filter(n => ids.indexOf(n.id) < 0)
      this.sourceData.push(...this.$refs.targetTable.selection)
    },
    addCraft() {
      let ids = this.$refs.sourceTable.selection.map(n => n.id)
      this.sourceData = this.sourceData.filter(n => ids.indexOf(n.id) < 0)
      this.targetData.push(...this.$refs.sourceTable.selection)
    },
    loadCraft() {
      listCraft(this.sourceForm).then(data => {
        this.sourceData = data
        //是其他项目进行过滤
        if (this.configForm.projectId === 12) {
          this.sourceData = this.sourceData.filter(n => n.illustrateType === 8)
        } else {
          this.sourceData = this.sourceData.filter(n => n.illustrateType !== 8)
        }
        this.targetData = this.budget.crafts.filter(n => n.id === this.configForm.projectId)[0].budgetUnits
        console.log(this.targetData)
        let ids = this.targetData.map(n => n.id)
        this.sourceData = this.sourceData.filter(n => ids.indexOf(n.id) < 0)
        this.isShow = true
      })
    },
    loadBasicData() {
      this.illustrateMap.set(1, '水电工')
      this.illustrateMap.set(2, '木工')
      this.illustrateMap.set(3, '瓦工')
      this.illustrateMap.set(4, '油漆工')
      this.illustrateMap.set(8, '杂项')
      listUnit().then((data) => {
        data.forEach(n => {
          this.unitMap.set(n.id, n.name)
        })
      })

    },
    configCraft(row) {
      if (!this.configForm.customerId) {
        this.$message({
          type: 'error',
          message: '请先选择客户!'
        })
        return
      }
      if (!this.configForm.engineerProjectId) {
        this.$message({
          type: 'error',
          message: '请先选择施工地址!'
        })
        return
      }
      this.$refs.lightCraftTable.toggleRowExpansion(row, true)
      this.configForm.projectId = row.id
      /*   listBindCrafts(this.configForm).then(n => {
          this.targetData = n
        }) */
      this.isDisabled=false
      this.loadCraft()

    },
    addBudget() {

      let p = this.budget.crafts.filter(n => {
        return n.id === this.configForm.projectId
      })
      this.$set(p[0], 'budgetUnits', this.targetData)
      this.$nextTick(() => {
        this.$refs.lightCraftTable.toggleRowExpansion(p[0], true)
      })
      this.isShow = false
    },
    handleAdd() {
      this.$bus.$emit('handleProjectAdd')
    },
    getCustomers(val) {
      if (!val) {
        return
      }
      this.loading = true
      listCustomer(val).then(data => {
        this.loading = false
        if (data.length > 0) {
          this.customerOptions = data.map(n => {
            return {
              value: n.id,
              label: n.name
            }
          })
        }
      })

    }
  }
}
</script>

<style scoped>
.click-disable{
  pointer-events: none;
}
.table_container {
  display: flex;
  align-items: center;
}

.button_group {
  margin: 0 20px;

}

.form-container {
  display: flex;
  justify-content: space-between;
}

.reset_btn {
  background-color: #722ed1;
  border: 1px solid #722ed1;
}

.reset_btn:hover {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}

.reset_btn:focus {
  background-color: #7849b7;
  border: 1px solid #7849b7;
}
</style>
